package com.lzx.reggie.service.impl

import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import com.lzx.reggie.common.CustomException
import com.lzx.reggie.entity.Category
import com.lzx.reggie.entity.Dish
import com.lzx.reggie.entity.Setmeal
import com.lzx.reggie.mapper.CategoryMapper
import com.lzx.reggie.service.CategoryService
import com.lzx.reggie.service.DishService
import com.lzx.reggie.service.SetmealService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service


@Service
class CategoryServiceImpl : ServiceImpl<CategoryMapper, Category>(), CategoryService {
    @Autowired
    private lateinit var dishService: DishService

    @Autowired
    private lateinit var setmealService: SetmealService

    /**
     * 根据id删除分类，删除之前需要进行判断
     * @param id
     */
    override fun remove(id: Long) {

        val count1 = dishService.count(
            //添加查询条件，根据分类id进行查询
            KtQueryWrapper(Dish::class.java).apply {
                eq(Dish::categoryId, id)
            })

        //查询当前分类是否关联了菜品，如果已经关联，抛出一个业务异常
        if (count1 > 0) {
            //已经关联菜品，抛出一个业务异常
            throw CustomException("当前分类下关联了菜品，不能删除")
        }

        val count2 = setmealService.count(
            //查询当前分类是否关联了套餐，如果已经关联，抛出一个业务异常
            KtQueryWrapper(Setmeal::class.java).apply {
                //添加查询条件，根据分类id进行查询
                eq(Setmeal::categoryId, id)
            })
        if (count2 > 0) {
            //已经关联套餐，抛出一个业务异常
            throw CustomException("当前分类下关联了套餐，不能删除")
        }

        //正常删除分类
        super<ServiceImpl>.removeById(id)
    }
}
